const app = getApp()
const promisify = require("../../utils/promisify")

Page({
  data: {
    favorite: []
  },
  onLoad: function () {
    let that = this
    that.onShow()
  },
  onShow: function () {
    let that = this
    promisify(wx.request)({
      url: `https://www.cumthing.world/cumthing/product-info/list` + app.ToParams({
        userId: app.globalData.userId
      }),
      method: "GET",
      header: {
        Authorization: app.globalData.token
      }
    }).then(
      data => {
        that.setData({
          favorite: data.data
        })
      }
    )
  },
  deleteItemListener: function (e) {
    let that = this
    let id = e.target.dataset.id
    let parentId = e.target.dataset.parentid
    let favorite = that.data.favorite
    let temp = JSON.parse(JSON.stringify(favorite))
    /**删除本地缓存 */
    favorite.forEach((item, index) => {
      if (item.productId === id) {
        temp.splice(index, 1)
      }
    })
    that.setData({
      favorite: temp
    })
    
    /**删除服务器收藏信息 */
    promisify(wx.request)({
      url: `https://www.cumthing.world/cumthing/product-info/add/collect` + app.ToParams({
        productId: id,
        userId: app.globalData.userId
      }),
      method: "GET",
      header: {
        'Authorization': app.globalData.token
      }
    }).then(
      data => {
        console.log(data)
      }
    )
  }
})